﻿<DemoPageSectionComponent Id="FileManagement-FileInput-UploadOnPage">
    <div class="upload-container">
        <span>Profile Picture</span>
        <div id="dropzone-external" class="card flex-box">
            @if(UploadComplete) {
                <img id="dropzone-image"
                     src="@($"data:{FileType};base64,{Convert.ToBase64String(FileBytes ?? Array.Empty<byte>())}")"
                     alt="DxFileInput uploaded image" />
            } else if(TotalBytesRead != 0) {
                <DxProgressBar CssClass="upload-progress"
                               Value="@TotalBytesRead"
                               MaxValue="@FileSize"
                               Label="@(TotalBytesRead == FileSize ? "Your image is almost ready..." : string.Empty)" />
            } else {
                <div id="dropzone-text" class="flex-box">
                    <span>Drag & Drop the desired file</span>
                    <span>…or click to browse for a file instead.</span>
                </div>
            }
        </div>
        <DxFileInput Visible="@false"
                     MaxFileSize="15000000"
                     FilesUploading="@OnFilesUploading"
                     CssClass="dropZone-owner"
                     ExternalSelectButtonCssSelector="#dropzone-external"
                     ExternalDropZoneCssSelector="#dropzone-external"
                     ExternalDropZoneDragOverCssClass="dropzone-hover"
                     AcceptedFileTypes="@AllowedFileExtensions">
        </DxFileInput>
    </div>

    @code {
        bool UploadComplete { get; set; } = false;
        byte[] FileBytes { get; set; }
        string FileType { get; set; }
        readonly List<string> AllowedFileExtensions = new() { ".jpg", ".jpeg", ".gif", ".png" };
        int FileSize { get; set; }
        int TotalBytesRead { get; set; }

        async Task OnFilesUploading(FilesUploadingEventArgs args) {
            UploadComplete = false;
            var file = args.Files[0];
            FileSize = (int)file.Size;
            FileBytes = new byte[FileSize];
            FileType = file.Type;

            var stream = file.OpenReadStream(file.Size);
            TotalBytesRead = 0;
            try {
                int bytesReadAsyncCount;
                while((bytesReadAsyncCount = await stream.ReadAsync(FileBytes, TotalBytesRead, FileSize - TotalBytesRead)) != 0) {
                    TotalBytesRead += bytesReadAsyncCount;
                    await InvokeAsync(StateHasChanged);
                }
            } finally {
                stream.Close();
            }
            UploadComplete = true;
            await InvokeAsync(StateHasChanged);

        }
    }

</DemoPageSectionComponent>
